<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="800" @ok="handleSubmit"
    class="csss" :footer="null">
    <div class="lingshi p-4">
      查询时间：
      <a-space direction="vertical" :size="12">
        <!-- <a-range-picker v-model:value="value4" :format="dateFormat"  style="width: 350px;"  /> -->
        <a-range-picker v-model:value="dateRange" :ranges="presetRanges" show-time @change="handleChange" />
      </a-space>
      <div class="historical" ref="chartCanvas"></div>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, Ref } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { useForm } from '/@/components/Form/index';
import { useECharts } from '/@/hooks/web/useECharts';
import { defHttp } from '@/utils/http/axios';
import dayjs from 'dayjs';

// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
  // schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 24 },
});
const dateRange = ref([dayjs().startOf('day'), dayjs().endOf('day')]);

const presetRanges = {
  '今天': [dayjs().startOf('day'), dayjs().endOf('day')],
  '昨天': [dayjs().subtract(1, 'day').startOf('day'), dayjs().subtract(1, 'day').endOf('day')],
  '前7天': [dayjs().subtract(7, 'day').startOf('day'), dayjs().endOf('day')],
  '前30天': [dayjs().subtract(30, 'day').startOf('day'), dayjs().endOf('day')],
  '前3个月': [dayjs().subtract(3, 'month').startOf('day'), dayjs().endOf('day')],
  '前半年': [dayjs().subtract(6, 'month').startOf('day'), dayjs().endOf('day')],
  // '前一年': [dayjs().subtract(1, 'year').startOf('day'), dayjs().endOf('day')],
};
//表单赋值
const id = ref();
const deviceId = ref();
const key = ref();
const fieldMap = ref({});
// x轴数据
const xData = ref([]);
// y轴数据
const yData = ref([]);
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  id.value = data.data.id;
  deviceId.value = data.data.deviceId;
  key.value = data.data.key;
  fieldMap.value = data.data.fieldMap;
  xData.value = []
  yData.value = []
  dateRange.value = [dayjs().startOf('day'), dayjs().endOf('day')];
  // 发起一次请求
  deviceData();
  title.value = fieldMap.value[key.value].name;

});
//设置标题
const title = ref('');
// 日期
function handleChange(dates, dateStrings) {
  if (dates) {
    const [start, end] = dates;
    const diffInDays = end.diff(start, 'day');
    console.log('Selected Range:', dates);
    console.log('Formatted Range:', dateStrings);
    console.log('Difference in Days:', diffInDays);
    // 在此处添加您要在日期范围改变时执行的代码
    let interval = 1800000;
    if (diffInDays >= 30 && diffInDays < 90) {
      interval = 43200000;
    } else if (diffInDays >= 90) {
      interval = 86400000;
    }
    deviceData(interval);
  } else {
    console.log('No range selected');
  }
}
// 获取设备数据
function deviceData(interval = 1800000) {
  defHttp
    .get({
      url: '/thingsUserDevice/listDeviceData/',
      params: {
        id: id.value,
        startTime: dayjs(dateRange.value[0]).format('YYYY-MM-DD HH:mm:ss'),
        endTime: dayjs(dateRange.value[1]).format('YYYY-MM-DD HH:mm:ss'),
        deviceId: deviceId.value,
        keys: key.value,
        limit: 1000,
        interval: interval,
        agg: 'AVG'
      },
    })
    .then((res) => {
      // console.log(res);
      let x = [];
      let y = [];
      res.timeseries.forEach((item) => {
        x.push(dayjs(item.ts).format('MM-DD HH:mm'));
        y.push(item.value);
      });
      xData.value = x;
      yData.value = y;

      //重置表单
      const { setOptions, } = useECharts(chartCanvas as Ref<HTMLDivElement>);
      const mapOption1 = {
        tooltip: {},
        legend: {
          data: [''],
        },
        xAxis: {
          type: 'category',
          data: xData.value,
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            name: fieldMap.value[key.value].name + fieldMap.value[key.value].unit,
            type: 'line',
            stack: 'Total',
            areaStyle: {},
            emphasis: {
              focus: 'series',
            },
            data: yData.value,
          },
        ],
      };

      // console.log('这里' + mapOption1.xAxis.data);
      mapOption1 && setOptions(mapOption1);
    });
}

const chartCanvas = ref<HTMLDivElement | null>(null);
onMounted(() => {
  if (true) {
    // const myChart = echarts.init(chartCanvas.value); // 使用容器元素的引用初始化echarts实例
  }
});
</script>

<style lang="less" scoped>
.lingshi {
  height: auto;
  background: #fff;
}

.historical {
  min-height: 310px;
  width: calc(100% - 40px);
  margin: 8% 20px 0px;
  border: 1px solid rgba(106, 121, 133, 0.1);
}
</style>
